package com.kefu.service.impl;

import com.kefu.common.redis.JedisUtils;
import com.kefu.common.redis.PubClient;
import com.kefu.mapper.KefuMapper;
import com.kefu.mapper.MsgMapper;
import com.kefu.model.Kefu;
import com.kefu.model.Msg;
import com.kefu.service.PubClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2016/11/25.
 */
@SuppressWarnings("SpringJavaAutowiringInspection")
@Service("pubClientService")
public class PubClientServiceImpl implements PubClientService {
    @Autowired
    private KefuMapper kefuMapper;
    @Autowired
    private MsgMapper msgMapper;

    public String msg_pub(String docId){
        final Kefu kefu=kefuMapper.findByDocId(docId);
        List<Kefu> kefus=kefuMapper.selectAll();
        Integer a=1;//判定中介值
        String b=null;//最终返回值
        for(Kefu kefu1:kefus) {
            String jedis = JedisUtils.pubsubChannels(kefu1.getId());
            if (jedis.equals("[" + kefu.getId() + "]")) {//如果活跃频道中有绑定客服id，就发布此频道
                PubClient.publishMsg(kefu.getId(), "toUID:" + kefu.getDocId());
                a = 2;
                b= "客服id：" + kefu.getId() + "    toUID:" + kefu.getDocId();
                break;
            }
        }
            if (a == 1) {//a=1说明活跃频道未有绑定客服id
                for ( Kefu kefu2 : kefus) {
                    String jedis1 = JedisUtils.pubsubChannels(kefu2.getId());
                    if (jedis1.equals("[" + kefu2.getId() + "]")) {
                        PubClient.publishMsg(kefu2.getId(), "toUID:" + kefu2.getDocId());
                        //当unsubscribe 方法被调用时，才执行以下代码
                        a = 2;
                        b = "客服id：" + kefu2.getId() + "    toUID:" + kefu.getDocId();
                        break;
                    }
                }
            }
            if (a == 1) {//说明没有活跃频道，直接存到数据库
                Msg msg = new Msg();
                msg.setId(UUID.randomUUID().toString());
                msg.setCreatedate(new Date());
                msg.setKefuId(kefu.getId());
                msg.setDocId(docId);
                msgMapper.add(msg);
                b= "无在线客服，直接存储。";
            }
            return b;
    }
}


